package com.bkhech.spring.security.example.domain;

import com.bkhech.spring.security.example.exception.ErrorCode;
import com.bkhech.spring.security.example.exception.enums.GlobalErrorCodeConstants;
import lombok.Data;
import org.springframework.util.Assert;

import java.io.Serializable;

/**
 * 响应对象
 *
 * @author guowm
 * @date 2023/1/10
 */
@Data
public class CommonResult<T> implements Serializable {
    /**
     * 错误码
     *
     * @see ErrorCode#getCode()
     */
    private int code;
    /**
     * 错误提示，用户可阅读
     *
     * @see ErrorCode#getMsg()
     */
    private String message;
    /**
     * 返回数据
     */
    private T data;

    private CommonResult() {
    }

    public static <T> CommonResult<T> success(T data) {
        CommonResult<T> response = new CommonResult<>();
        response.setCode(200);
        response.setData(data);
        return response;
    }

    public static <T> CommonResult<T> error(String message) {
        CommonResult<T> commonResult = new CommonResult<>();
        commonResult.setCode(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode());
        commonResult.setMessage(message);
        return commonResult;
    }

    public static <T> CommonResult<T> error(ErrorCode errorCode) {
        return error(errorCode.getCode(), errorCode.getMsg());
    }


    public static <T> CommonResult<T> error(int code, String message) {
        Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code), "code 必须是错误的！");
        CommonResult<T> commonResult = new CommonResult<>();
        commonResult.setCode(code);
        commonResult.setMessage(message);
        return commonResult;
    }

}
